package repositories

import (
	"context"
	"time"

	"github.com/google/uuid"
	"gitverse.ru/pahtll/denisovich/internal/models"
	"go.mongodb.org/mongo-driver/mongo"
)

type ReviewRepository struct {
	db *mongo.Collection
}

func NewReviewRepository(db *mongo.Database, collection string) *ReviewRepository {
	return &ReviewRepository{
		db: db.Collection(collection),
	}
}

func (c ReviewRepository) CreateReview(ctx context.Context, Review *models.Review) error {
	res, err := c.db.InsertOne(ctx, &models.Review{
		Id:         uuid.New(),
		Content:    Review.Content,
		SenderName: Review.SenderName,
		SendTime:   time.Now(),
	})
	if err != nil {
		return err
	}

	Review.Id = res.InsertedID.(uuid.UUID)

	return nil
}

func (c ReviewRepository) GetReviewById(ctx context.Context, id uuid.UUID) (*models.Review, error) {
	Review := models.Review{}
	err := c.db.FindOne(ctx, models.Review{Id: id}).Decode(&Review)
	if err != nil {
		return nil, err
	}

	return &Review, nil
}

func (c ReviewRepository) GetReviewsBySenderName(ctx context.Context, senderName string) ([]*models.Review, error) {
	Review := []*models.Review{}

	cursor, err := c.db.Find(ctx, models.Review{SenderName: senderName})
	if err != nil {
		return nil, err
	}

	if err = cursor.All(ctx, &Review); err != nil {
		return nil, err
	}

	return Review, nil
}

func (c ReviewRepository) GetAllReviews(ctx context.Context) ([]*models.Review, error) {
	Review := []*models.Review{}

	cursor, err := c.db.Find(ctx, models.Review{})
	if err != nil {
		return nil, err
	}

	if err = cursor.All(ctx, &Review); err != nil {
		return nil, err
	}

	return Review, nil
}

func (c ReviewRepository) DeleteReview(ctx context.Context, id uuid.UUID) error {
	_, err := c.db.DeleteOne(ctx, models.Review{Id: id})
	if err != nil {
		return err
	}

	return nil
}
